package com.zjsru.service.impl;

import com.zjsru.clients.ProductClient;
import com.zjsru.clients.UserClient;
import com.zjsru.mapper.OrderMapper;
import com.zjsru.pojo.Order;
import com.zjsru.pojo.Result;
import com.zjsru.pojo.User;
import com.zjsru.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    UserClient userClient;
    @Qualifier("com.zjsru.clients.ProductClient")
    @Autowired
    ProductClient productClient;

    @Override
    public Order queryOrderById(Long order_Id) {
        Order order = orderMapper.queryOrderById(order_Id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
//        Result result = userClient.queryUserById(order.getUser_Id());
//        User user = (User) result.getData();
//        //把查询出来的用户信息（user对象）封装到order中的user属性中
//        order.setUser(user);
        return order;
    }

    @Override
    public List<Order> queryOrderByUserId(Long user_Id) {
        return orderMapper.queryOrderByUserId(user_Id);
    }

    @Override
    public Order createOrder(Order order) {
        //验证用户有效性
        if(userClient.checkStatus(order.getUser().getUsername())){
            //    扣减库存
            if (productClient.updateProductCount(order.getNum(), order.getProduct_Id()).getCode() != 200){
                //回滚事务
                throw new RuntimeException("库存不足");
            }
            return orderMapper.createOrder(order);
        }
        else {
            throw new RuntimeException("用户不存在");
        }
    }

    @Override
    public void deleteOrder(Long order_Id) {
        orderMapper.deleteOrder(order_Id);
    }

    @Override
    public void updateOrderStatus(Long order_Id) {
        orderMapper.updateOrderStatus(order_Id);
    }

    @Override
    public List<Order> queryOrderByStatus(String status) {
        return orderMapper.queryOrderByStatus(status);
    }
}
